﻿// This code is released under the BSD license.
// This code is released under the BSD license.
namespace PugLib.UnitTest
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using Extensions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class ActionExtensionsTest
    {
        internal static int _accumulate = 0;

        [TestMethod]
        public void MakeParallelTest()
        {
            Action<int> f = null;
            for (int i = 0; i < 8; i++)
            {
                f += Thread.Sleep;
            }
            Stopwatch ws = Stopwatch.StartNew();
            if (f != null)
            {
                f(250);
                Console.WriteLine("ser: {0:f3}", ws.Elapsed.TotalMilliseconds);
                f = f.MakeParallel();
                ws = Stopwatch.StartNew();
                f(250);
                Console.WriteLine("par: {0:f3}", ws.Elapsed.TotalMilliseconds);
            }
        }

        [TestMethod]
        public void ExecuteInMutexTest()
        {
            const string mutexId = "Global\\{B22CA031-0FC6-473f-8770-4F499301796D}";
            ThreadPool.QueueUserWorkItem(AccumulateInMutext, mutexId);
            Thread.Sleep(1000);
            ThreadPool.QueueUserWorkItem(AccumulateInMutext, mutexId);
            Assert.AreEqual(1, _accumulate);
            Thread.Sleep(15000);
            Assert.AreEqual(2, _accumulate);
        }

        private static void AccumulateInMutext(object mutexId)
        {
            Action action = Accumulate;
            action.ExecuteInMutexWithSubsequentWaits((string)mutexId);
        }

        private static void Accumulate()
        {
            _accumulate++;
            Thread.Sleep(5000);
        }
    }
}